package cn.zzzly.sql;

import cn.zzzly.utils.JdbcUtils;

import java.sql.*;

/*
 * @author Zzzyl
 * @date 2020-10-27
 */
public class Sql {
    //把账号和密码存入数据库
    public boolean insert(String username, String password, String qq, String message, String time){
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String sql = "insert into user values(null,'"+username+"','"+password+"','"+qq+"','"+message+"','"+time+"')";
        int count = 0;
        try{
            conn = JdbcUtils.getConnection();
            //获取执行sql对象 statement
            stmt = conn.createStatement();
            //执行sql
            count = stmt.executeUpdate(sql);
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.release(conn,stmt,rs);
        }
        return count > 0;
    }

    //查询数据库是否已收录账号
    public boolean select(String username) throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String sql = "select * from user where username = '" + username + "'";
        try {
            conn = JdbcUtils.getConnection();
            //获取执行sql对象 statement
            stmt = conn.createStatement();
            //执行sql
            rs = stmt.executeQuery(sql);
            return rs.next();

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
           JdbcUtils.release(conn,stmt,rs);
        }
        return true;
    }
    //查询已经有多少人了
    public int rowCount() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String sql = "select * from user";
        int rowCount = 0;
        try{
            conn = JdbcUtils.getConnection();
            //获取执行sql对象 statement
            stmt = conn.createStatement();
            //执行sql
            rs = stmt.executeQuery(sql);
            rs.last();
            rowCount = rs.getRow();
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.release(conn,stmt,rs);
        }
        return rowCount;
    }
}
